package com.cloud.lan.integration.submail.mms.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cloud.lan.integration.submail.common.CommonService;
import com.cloud.lan.integration.submail.common.HttpDeleteWithBody;
import com.cloud.lan.integration.submail.common.SubMailConstants;
import com.cloud.lan.integration.submail.mms.entity.MmsTemplateHandleRes;
import com.cloud.lan.integration.submail.mms.entity.MmsTemplateModel;
import com.cloud.lan.integration.submail.mms.entity.MmsTemplateQueryRes;
import com.cloud.lan.integration.submail.mms.service.MmsTemplateService;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.TreeMap;

import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * Created by zhouquan on 2022/4/3.
 */
@Slf4j
@Service
public class MmsTemplateServiceImpl implements MmsTemplateService{

    @Autowired
    private CommonService commonService;

    @Override
    public MmsTemplateQueryRes query(MmsTemplateModel model) {
        try{
            TreeMap<String, String> requestData = new TreeMap<>();
            requestData.put("appid", SubMailConstants.MMS_APPID);
            requestData.put("sign_version", SubMailConstants.SIGN_VERSION);
            if(StringUtils.isNotBlank(model.getTemplateId())){
                requestData.put("template_id", model.getTemplateId());
            }
            commonService.buildSignature(SubMailConstants.MMS_APPID, SubMailConstants.MMS_APPKEY, SubMailConstants.SIGNTYPE, requestData);

            String urlGet = SubMailConstants.MMS_TEMPLATE_URL + "?";
            for (Map.Entry<String, String> entry : requestData.entrySet()) {
                String key = entry.getKey();
                Object value = entry.getValue();
                if (value instanceof String) {
                    urlGet += key + "=" + value + "&";
                }
            }
            urlGet = urlGet.substring(0, urlGet.length() - 1);
            HttpGet httpGet = new HttpGet(urlGet);
            log.info("彩信模板.查询.req:[{}]",JSON.toJSONString(httpGet));
            String httpRes = commonService.httpRequest(httpGet);
            MmsTemplateQueryRes queryRes = JSON.parseObject(httpRes,MmsTemplateQueryRes.class);
            if(Objects.nonNull(queryRes) && Objects.nonNull(queryRes.getTemplate())
                    && ObjectUtil.isEmpty(queryRes.getTemplates())){
                List<MmsTemplateModel> templates = new ArrayList<>();
                templates.add(queryRes.getTemplate());
                queryRes.setTemplates(templates);
            }
            log.info("彩信模板.查询.res:[{}]",JSON.toJSONString(queryRes));
            return queryRes;
        }catch (Exception e){
            log.info("彩信模板.查询.error",e);
            return MmsTemplateQueryRes.error("MMSQUERY001",e.getMessage());
        }
    }

    @Override
    public MmsTemplateHandleRes create(MmsTemplateModel model) {
        try{
            TreeMap<String, String> requestData = new TreeMap<>();
            requestData.put("appid", SubMailConstants.MMS_APPID);
            requestData.put("sign_version", SubMailConstants.SIGN_VERSION);
            commonService.buildSignature(SubMailConstants.MMS_APPID, SubMailConstants.MMS_APPKEY, SubMailConstants.SIGNTYPE, requestData);
            requestData.put("mms_type", "video");
            requestData.put("mms_title", model.getMmsTitle());
            requestData.put("mms_signature", model.getMmsSignature());
            requestData.put("mms_subject", model.getMmsSubject());
            requestData.put("mms_content", JSON.toJSONString(model.getContentList()));

            HttpPost httpPost = new HttpPost(SubMailConstants.MMS_TEMPLATE_URL);
            httpPost.addHeader("charset", "UTF-8");
            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Content-Type", "application/json");
            StringEntity postEntity = new StringEntity(JSONObject.toJSONString(requestData), "UTF-8");
            httpPost.setEntity(postEntity);
            log.info("彩信模板.创建.req:[{}]",JSON.toJSONString(httpPost));
            String httpRes = commonService.httpRequest(httpPost);
            MmsTemplateHandleRes handleRes = JSON.parseObject(httpRes,MmsTemplateHandleRes.class);
            log.info("彩信模板.创建.res:[{}]",JSON.toJSONString(handleRes));
            return handleRes;
        }catch (Exception e){
            log.info("彩信模板.创建.error",e);
            return MmsTemplateHandleRes.error("MMSCREATE001",e.getMessage());
        }
    }

    @Override
    public MmsTemplateHandleRes update(MmsTemplateModel model) {
        try{
            TreeMap<String, String> requestData = new TreeMap<>();
            requestData.put("appid", SubMailConstants.MMS_APPID);
            requestData.put("sign_version", SubMailConstants.SIGN_VERSION);
            commonService.buildSignature(SubMailConstants.MMS_APPID, SubMailConstants.MMS_APPKEY, SubMailConstants.SIGNTYPE, requestData);
            requestData.put("template_id", model.getTemplateId());
            requestData.put("mms_type", "video");
            requestData.put("mms_title", model.getMmsTitle());
            requestData.put("mms_signature", model.getMmsSignature());
            requestData.put("mms_subject", model.getMmsSubject());
            requestData.put("mms_content", JSON.toJSONString(model.getContentList()));

            HttpPut httpput = new HttpPut(SubMailConstants.MMS_TEMPLATE_URL);
            httpput.addHeader("charset", "UTF-8");
            httpput.setHeader("Accept", "application/json");
            httpput.setHeader("Content-Type", "application/json");
            StringEntity entity = new StringEntity(JSONObject.toJSONString(requestData), "UTF-8");
            httpput.setEntity(entity);
            log.info("彩信模板.更新.req:[{}]",JSON.toJSONString(httpput));
            String httpRes = commonService.httpRequest(httpput);;
            MmsTemplateHandleRes handleRes = JSON.parseObject(httpRes,MmsTemplateHandleRes.class);
            log.info("彩信模板.更新.res:[{}]",JSON.toJSONString(handleRes));
            return handleRes;
        }catch (Exception e){
            log.info("彩信模板.更新.error",e);
            return MmsTemplateHandleRes.error("MMSUPDATE001",e.getMessage());
        }
    }

    @Override
    public MmsTemplateHandleRes del(MmsTemplateModel model) {
        try{
            TreeMap<String, String> requestData = new TreeMap<>();
            requestData.put("appid", SubMailConstants.MMS_APPID);
            requestData.put("sign_version", SubMailConstants.SIGN_VERSION);
            commonService.buildSignature(SubMailConstants.MMS_APPID, SubMailConstants.MMS_APPKEY, SubMailConstants.SIGNTYPE, requestData);
            requestData.put("template_id", model.getTemplateId());

            String entityStr = "";
            for (Map.Entry<String, String> entry : requestData.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();
                entityStr += key + "=" + value + "&";
            }
            HttpDeleteWithBody httpDelete = new HttpDeleteWithBody(SubMailConstants.MMS_TEMPLATE_URL);
            HttpEntity delEntity = new StringEntity(entityStr);
            httpDelete.setEntity(delEntity);
            log.info("彩信模板.删除.req:[{}]",JSON.toJSONString(httpDelete));
            String httpRes = commonService.httpRequest(httpDelete);
            MmsTemplateHandleRes handleRes = JSON.parseObject(httpRes,MmsTemplateHandleRes.class);
            log.info("彩信模板.删除.res:[{}]",JSON.toJSONString(handleRes));
            return handleRes;
        }catch (Exception e){
            log.info("彩信模板.删除.error",e);
            return MmsTemplateHandleRes.error("MMSDEL001",e.getMessage());
        }
    }

}
